//
//  QWAppContext.m
//  WJAppContext-example
//
//  Created by Yunhai.Wu on 15/11/2.
//  Copyright (c) 2015年 WJ. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "QWAppContext.h"
#import "IQWAppNotifyHandler.h"
#import "QWSingleton.h"
#import "QWAppContextConfig.h"

NSString * const QWAppContextSyncDidLaunchingNotification = @"QWAppContextSyncDidLaunchingNotification";

@interface QWAppContext ()
@property (nonatomic, strong) NSMutableDictionary *handlerMap;//Key:NSString Value:NSArray

AS_SINGLETON(QWAppContext)

@end

@implementation QWAppContext

DEF_SINGLETON_INIT(QWAppContext)

+(void) registerApp:(void (^)(QWAppContextConfig* config)) configBlock {
    /**
     *  发送程序启动通知
     */
    [[QWAppContext sharedInstance] postDidLauningNotify];
    
    QWLogDebug(@"QWAppContext register ...");
    
    QWLogDebug(@"QWAppContext config begin ...");
    configBlock([QWAppContextConfig sharedInstance]);
    QWLogDebug(@"QWAppContext config end ...");
}

-(void) postDidLauningNotify {
    [[NSNotificationCenter defaultCenter] postNotificationName:QWAppContextSyncDidLaunchingNotification object:nil];
}

-(void) handleNotification:(NSNotification*) notification {
    NSString *notifyName = [notification name];
    NSArray *handlers = _handlerMap[notifyName];
    for (id<IQWAppNotifyHandler> handler in handlers) {
        [handler handle:notification];
    }
}

-(void) singleInit {
    
    self.handlerMap = [[NSMutableDictionary alloc] init];
    
    
    
    NSArray *handlers = [[QWAppContextConfig sharedInstance] notifyHandles];
    
    for (Class clazz in handlers) {
        id<IQWAppNotifyHandler> handler = [clazz getInstance];
        NSString *appNotifyName = [handler appNotifyName];
        if (appNotifyName) {
            NSMutableArray *handlers = _handlerMap[appNotifyName];
            if (handlers == nil) {
                handlers = [[NSMutableArray alloc] init];
                [_handlerMap setObject:handlers forKey:appNotifyName];
                [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:appNotifyName object:nil];
            }
            [handlers addObject:handler];
        }
    }
}

-(void)deallocObject {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
